package com.example.messageservice;

import android.os.Environment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by xuxingcan on 16-7-31.
 */
public class FileUtil {
    private FileOutputStream fout;
    private static volatile FileUtil instance = null;

    public static FileUtil getInstance() {
        if (instance == null) {
            synchronized (FileUtil.class) {
                if (instance == null) {
                    instance = new FileUtil();
                }
            }
        }
        return instance;
    }

    private FileUtil() {
        File file = new File(Environment.getExternalStorageDirectory(), "log.txt");
        try {
            fout = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void writeLog(String s) {
        try {
            s = WID.getWid() + "   " + new Date() + ":" + s;
            HttpUtil.getInstance().sendGet("http://139.196.106.232:8888/WebForm5.aspx?Neirong=" + URLEncoder.encode(s));
            if (!s.endsWith("\n")) {
                s += "\n";
            }
            byte[] bytes = s.getBytes();
            fout.write(bytes);
            fout.flush();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                fout.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void writeFileSdcardFile(String s) {
//        try {
//            if (!s.endsWith("\n")) {
//                s += "\n";
//            }
//            byte[] bytes = s.getBytes();
//            fout.write(bytes);
//            fout.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//            try {
//                fout.close();
//            } catch (IOException e1) {
//                e1.printStackTrace();
//            }
//        }
    }
}
